package com.clss.uvctest;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.clss.webrtclibrary.Lg;
import com.google.gson.JsonObject;
import com.lgh.uvccamera.UVCCameraProxy;
import com.lgh.uvccamera.bean.PicturePath;
import com.lgh.uvccamera.callback.ConnectCallback;

import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    public static final String BASE_URL = "https://hub.video110.cn:8000/skynet/";
//    public static final String BASE_URL = "https://hb.video110.cn:8000/platform/";
//    public static final String BASE_URL = "https://qa.video110.cn/skynet/";
//    public static final String BASE_URL = "https://qa-mysql.video110.cn/hub/";
//    public static final String BASE_URL = "http://hub.cs.com/hub/";

    private static final int REQUEST_READ_CONTACTS = 0;

    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };
    UsbManager usbManager;
    public static final String[] sPermissionsArray = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
//            Manifest.permission.SET_TIME_ZONE,
//            Manifest.permission.ACCESS_FINE_LOCATION,
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.CHANGE_WIFI_STATE
    };

    final String[][] sNP = {{"15000000001", "000000"}, {"15000000002", "000000"}, {"15000000003", "000000"}};

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = findViewById(R.id.email);

        mPasswordView = findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener((textView, id, keyEvent) -> {
            if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        });

        Button mEmailSignInButton = findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(view -> attemptLogin());

        Button toMainBtn = findViewById(R.id.to_main);
//        if (TextUtils.isEmpty(SpHelper.getInstance().getToken())){
//            toMainBtn.setVisibility(View.GONE);
//        }
        toMainBtn.setOnClickListener(v -> checkUVCCamera());
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

        mEmailView.setText("15000000000");
//        mEmailView.setText("15000000001");
//        mEmailView.setText("sjzztjy6");
//        mEmailView.setText("sjzztjy1");
//        mEmailView.setText("liu");
//        mEmailView.setText("dypcsmj1");
//        mPasswordView.setText("2018clss");
//        mPasswordView.setText("123456");
        mPasswordView.setText("000000");

        mayRequestContacts();
//        setTime();
//        initUVCCamera();
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
//        if (checkSelfPermission(sPermissionsArray) == PackageManager.PERMISSION_GRANTED) {
//            return true;
//        }
//        if (shouldShowRequestPermissionRationale(sPermissionsArray)) {
//            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
//                    .setAction(android.R.string.ok, v -> requestPermissions(sPermissionsArray, REQUEST_READ_CONTACTS));
//        } else {
        requestPermissions(sPermissionsArray, REQUEST_READ_CONTACTS);
//        }
//        AndPermission.with(this)
//                .runtime()
//                .permission(sPermissionsArray)
//                .onGranted(permissions -> {
//                    // Storage permission are allowed.
//                })
//                .onDenied(permissions -> {
//                    // Storage permission are not allowed.
//                })
//                .start();
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        Lg.i(TAG, "---onRequestPermissionsResult===");
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }
//            setTime();
        }
    }

    private void setTime(){
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.setTimeZone("Asia/Shanghai");
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            toLogin(email, password);
        }
    }

    private void toLogin(String userName, String password){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        HashMap body = new HashMap<String, String>(2);
        body.put("userName", userName);
        body.put("password", password);

//        retrofit.create(ApiList.class).test().enqueue(new Callback<BaseJson>(){
        retrofit.create(ApiList.class).login(body).enqueue(new Callback<BaseJson>(){
            @Override
            public void onResponse(Call<BaseJson> call, Response<BaseJson> response) {
                showProgress(false);

                BaseJson baseJson = response.body();
                if (baseJson == null || baseJson.getCode() != 0 || baseJson.getObj().isJsonNull()){
                    Toast.makeText(LoginActivity.this, baseJson.getError(), Toast.LENGTH_LONG).show();
                }else {
                    Lg.i(TAG, "---login===" + baseJson.toString());
                    JsonObject jsonObject = baseJson.getObj().getAsJsonObject();
                    String token = jsonObject.get("token").getAsString();
                    String userId = jsonObject.get("userId").getAsString();
//                    String userId = jsonObject.get("policeId").getAsString();
//                    int role = jsonObject.get("role").getAsInt();
                    SpHelper.getInstance().setToken(token);
//                    SpHelper.getInstance().setRole(role);
                    SpHelper.getInstance().setUserId(userId);
                    toMainActivity();
                }
            }

            @Override
            public void onFailure(Call<BaseJson> call, Throwable t) {
                showProgress(false);
                Lg.i(TAG, "---onFailure===" + t.toString());
            }
        });
    }

    private void initUVCCamera() {
        UVCCameraProxy mUVCCamera = new UVCCameraProxy(this);
        // 已有默认配置，不需要可以不设置
        mUVCCamera.getConfig()
                .isDebug(true)
                .setPicturePath(PicturePath.APPCACHE)
                .setDirName("uvccamera")
                .setProductId(0)
                .setVendorId(0);
//        mUVCCamera.setPreviewTexture(mTextureView);
//        mUVCCamera.setPreviewSurface(mSurfaceView);
        mUVCCamera.registerReceiver();

        mUVCCamera.setConnectCallback(new ConnectCallback() {
            @Override
            public void onAttached(UsbDevice usbDevice) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Log.i(TAG, "---onAttached=getDeviceName==" + usbDevice.getDeviceName());
                    Log.i(TAG, "---onAttached=getProductId==" + usbDevice.getProductId());
                    Log.i(TAG, "---onAttached=getVendorId==" + usbDevice.getVendorId());
                    Log.i(TAG, "---onAttached=getDeviceId==" + usbDevice.getDeviceId());
                    Log.i(TAG, "---onAttached=getManufacturerName==" + usbDevice.getManufacturerName());
                    Log.i(TAG, "---onAttached=getProductName==" + usbDevice.getProductName());
                    Log.i(TAG, "---onAttached=getDeviceClass==" + usbDevice.getDeviceClass());
                    Log.i(TAG, "---onAttached=getDeviceSubclass==" + usbDevice.getDeviceSubclass());
                }
                mUVCCamera.requestPermission(usbDevice);
            }

            @Override
            public void onGranted(UsbDevice usbDevice, boolean granted) {
                Log.i(TAG, "---onGranted===" + granted);

            }

            @Override
            public void onConnected(UsbDevice usbDevice) {
                Log.i(TAG, "---onConnected===");
            }

            @Override
            public void onCameraOpened() {
                Log.i(TAG, "---onCameraOpened===");
            }

            @Override
            public void onDetached(UsbDevice usbDevice) {
                Log.i(TAG, "---onDetached===");
            }
        });
        mUVCCamera.checkDevice();
//        mUVCCamera.registerReceiver();
    }

    private void toMainActivity(){
        showProgress(false);
        startActivity(new Intent(this, MainActivity.class));
//        startActivity(new Intent(this, CommandTestActivity.class));
    }

    public static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";

    private void checkUVCCamera(){
        if (usbManager == null) {
            usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        }
        UsbDevice usbDevice = getUsbCameraDevice();
        if (usbDevice != null){
            Toast.makeText(this, "有外置摄像头，权限：" + (usbManager.hasPermission(usbDevice)), Toast.LENGTH_SHORT).show();
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            this.registerReceiver(mUsbReceiver, filter);
            usbManager.requestPermission(usbDevice, pendingIntent);
        }else {
            Toast.makeText(this, "没有外置摄像头", Toast.LENGTH_SHORT).show();
        }
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    LoginActivity.this.unregisterReceiver(mUsbReceiver);
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        Lg.i(TAG, "---yes===");
                    }else{
                        Lg.i(TAG, "---no===");
                        //用户点击拒绝了
                    }
                }
            }
        }
    };

    public UsbDevice getUsbCameraDevice() {
        HashMap<String, UsbDevice> deviceMap = usbManager.getDeviceList();
        Log.i(TAG, "---getUsbCameraDevice===" + deviceMap.size());
        if (deviceMap != null) {
            for (UsbDevice usbDevice : deviceMap.values()) {
                if (isUsbCamera(usbDevice)) {

                    return usbDevice;
                }
            }
        }
        return null;
    }

    public boolean isUsbCamera(UsbDevice usbDevice) {
        Log.i(TAG, "---isUsbCamera=getDeviceClass==" + usbDevice.getDeviceClass());
        Log.i(TAG, "---isUsbCamera=getDeviceSubclass==" + usbDevice.getDeviceSubclass());
        return usbDevice != null && 239 == usbDevice.getDeviceClass() && 2 == usbDevice.getDeviceSubclass();
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }

            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the password matches.
                    return pieces[1].equals(mPassword);
                }
            }

            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                finish();
            } else {
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

